<script>
import { deepClone } from '@/utils/index'
import { ComponentConfigList, Components } from './custom/config.js'
import CustomeTabs from './Tabs.vue'
import authorizeMixin from "@/mixins/authorize";

const ComponentList = ComponentConfigList
Components['CustomeTabs'] = CustomeTabs;

export default {
  name: 'FormParser',
    mixins: [authorizeMixin],
  components: Components,
  props: {
    conf: {
      type: Object,
      required: true
    },
    formData: {
      type: Object
    },
    formInfos: {
      type: Object
    },
    isEdit: {
      type: Number
    },
    fromPage: {//来自页面
      type: String,
      default:()=>{
        return ""
      }
    },
  },
  data() {
    return {
      formOperationObject: {
        formModel: {}, // 绑定数据
        formRules: {}, // 绑定规则
        mainTableName: ''
      },
      formConf: {},
      userInfo: {},
      autoCompleteConf: {},
      slots: [],
      checkboxField:{}
    }
  },
  created() {
	this.changeJurisdiction();
  },
   render(h) {
     
    return (
      <el-row gutter={this.formConf.gutter}>
        <el-form
          size={this.formConf.size}
          label-position={this.formConf.labelPosition}
          disabled={this.formConf.disabled}
          label-width={`${this.formConf.labelWidth}px`}
          ref={this.formConf.formRef}
          props={{
            model: this.formOperationObject.formModel[
              this.formOperationObject.mainTableName
            ]
          }}
          rules={this.formOperationObject.formRules}
        >
          {this.renderForm(h)}
        </el-form>
        {this.slots}
      </el-row>
    )
  },
  mounted(){
    this.$event.$on('openFilterableDataDialog',conf=>{
      this.autoCompleteConf = conf;
      this.slots = [];
      var listeners = {
        onHandler: conf.avueType=="mutiple-popup"?this.mutipleFilterableCallBack:this.filterableCallBack
      }

      this.slots.push( 
        <filterable-data-list 
        conf={this.autoCompleteConf}
		type={conf.avueType=="mutiple-popup"?'mutiple':'single'}
        {...{ on: listeners }}>
        </filterable-data-list>
      );
    });
  },
  methods: {
    changeJurisdiction(){
      if(this.fromPage=='preview'){
        this.formConf = deepClone(this.conf)
      }else{
		//非工作流 读取字段权限
        let formConf = deepClone(this.conf);
        let fields = formConf.fields;
        let tempfields = [];
        if(fields.length>0){
          fields.forEach(ele => {
            if(ele.__config__){
              if(ele.__config__.componentName=="avue-tabs"){
                let tempEle = deepClone(ele);
                 tempEle.__config__.childrenObj = {};
                if (ele.__config__.childrenObj) {
                let obj = ele.__config__.childrenObj;
                let childrenObj = {};
                for (var key in obj) {
                   let tabs = [];
                  if (obj[key].length > 0) {
                    obj[key].forEach((ele1) => {
					  if(ele1.__type__== "opinion") return;   //意见簿在非工作流表单中不显示
                      if(ele1.__config__.componentName &&ele1.__config__.componentName=="table"){
                        //子表单权限
                        if(this.formEnCodeList[ele1.__config__.bindTable]){
                          let formSubEnCodeList =this.formEnCodeList[ele1.__config__.bindTable];//子表单权限
                          let authorityChildrenList = new Map();
                          if(formSubEnCodeList.length>0){
                            formSubEnCodeList.forEach(fieldsId=>{
                              authorityChildrenList.set(fieldsId,{
                                required:true,
                                view:true,
                                edit:true,
                              });
                            });
                          }
                          if(ele1.__config__.children&&ele1.__config__.children.length>0){
                            ele1.__config__.children = ele1.__config__.children.map(ele2=>{
                              if( authorityChildrenList.has(ele2.__config__.bindTableField)){
                                let temp = authorityChildrenList.get(ele2.__config__.bindTableField);
                                // ele2.__config__.required = temp.required;
                                ele2.__config__.view = temp.view;
                                ele2.__config__.edit = temp.edit;
                              }else{
                                ele2.__config__.required = true;
                                ele2.__config__.view = false;
                                ele2.__config__.edit = true;
                              }
                              return ele2;
                            });
                          }
                        }
                         tabs.push(ele1);
                      }
                      else if(ele1.__config__.bindTableField){
                          if(this.formEnCodeList[ele1.__config__.bindTableField]){
                            tabs.push(ele1);
                          }
                        }else{
                          tabs.push(ele1);
                        }
                    });
                  }
                  childrenObj[key] = tabs;
                }
                tempEle.__config__.childrenObj = childrenObj;
                 tempfields.push(tempEle);
              }
              }else if(ele.__config__.componentName &&ele.__config__.componentName=="table"){
                  //子表单权限
                  if(this.formEnCodeList[ele.__config__.bindTable]){
                    let formSubEnCodeList =this.formEnCodeList[ele.__config__.bindTable];//子表单权限
                    let authorityChildrenList = new Map();
                    if(formSubEnCodeList.length>0){
                      formSubEnCodeList.forEach(fieldsId=>{
                        authorityChildrenList.set(fieldsId,{
                          required:true,
                          view:true,
                          edit:true,
                        });
                      });
                    }
                    if(ele.__config__.children&&ele.__config__.children.length>0){
                      ele.__config__.children = ele.__config__.children.map(ele2=>{
                        if( authorityChildrenList.has(ele2.__config__.bindTableField)){
                          let temp = authorityChildrenList.get(ele2.__config__.bindTableField);
                          // ele2.__config__.required = temp.required;
                          ele2.__config__.view = temp.view;
                          ele2.__config__.edit = temp.edit;
                        }else{
                          ele2.__config__.required = true;
                          ele2.__config__.view = false;
                          ele2.__config__.edit = true;
                        }
                        return ele2;
                      });
                    }
                    tempfields.push(ele);
                  }else{
                      tempfields.push(ele);
                  }
              }else{
				if(ele.__type__== "opinion") return;   //意见簿在非工作流表单中不显示
                if(ele.__config__.bindTableField){
                  if(this.formEnCodeList[ele.__config__.bindTableField]){
                    tempfields.push(ele);
                  }
                }else{
                  tempfields.push(ele);
                }
              }
            }
          });
        }
        formConf.fields = tempfields;
        this.formConf = formConf
      }
      if (!this.formConf.fields) {
      this.$message.error('表单配置异常，请检查数据格式')
      return false
    }
    this.userInfo = localStorage.getItem('avue-userInfo')
      ? JSON.parse(localStorage.getItem('avue-userInfo')).content
      : {}
    this.formConf.formRef = this.formConf.formRef?this.formConf.formRef:'refs'+Math.floor((Math.random()*100)+1);
    this.changeData()
    },
	mutipleFilterableCallBack(data){
		if(!this.autoCompleteConf){
		  return false;
		}
		//弹窗关闭前回填数据  如果有选择数据项
		if(data){
		  let fields = this.formConf.fields;
		  if(this.autoCompleteConf.autoBindFields){
		    let autoBindFields = JSON.parse(this.autoCompleteConf.autoBindFields) || {};
			let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName':this.autoCompleteConf.showField;
			let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue':this.autoCompleteConf.saveField;
		    if (data && data.length > 0) {
				let arr = [],arr2=[]
				data.forEach(it => {
				  arr.push(it[showField])
				  arr2.push(it[saveField])
				})
				//自己赋值
				this.selfSetDefaultVal(fields,autoBindFields,arr.join(','),arr2.join(','),this.autoCompleteConf.formId);
			  }
		    
		  }
		}
		//关闭弹窗
		this.slots = [];
	},
    filterableCallBack(data){
      if(!this.autoCompleteConf){
        return false;
      }
      
      //弹窗关闭前回填数据  如果有选择数据项
      if(data){
		  
        let fields = this.formConf.fields;
        if(this.autoCompleteConf.autoBindFields){
          let autoBindFields = JSON.parse(this.autoCompleteConf.autoBindFields) || {};
          let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName':this.autoCompleteConf.showField;
		  let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue':this.autoCompleteConf.saveField;
          this.setDefaultVal(fields,autoBindFields,data);
          //自己赋值
          this.selfSetDefaultVal(fields,autoBindFields,data[showField],data[saveField],this.autoCompleteConf.formId);
        }
      }
      //emit 改变值
      this.$event.$emit('updateFormConf',this.formConf);
      //关闭弹窗
      this.slots = [];
    },
    setDefaultVal(fields,autoBindFields,data){
      fields.map((item,index)=>{
        if(item?.__config__?.componentName == 'avue-tabs'){
          let childrenObj = item?.__config__?.childrenObj || {};
          for(let key in childrenObj){
            let children = childrenObj[key];
            this.setDefaultVal(children,autoBindFields,data);
          }
        }else{
          //找到对应formId 元素  key值为存储的对应formId         
		  if(Object.prototype.toString.call(autoBindFields) === '[object Array]'){
			  autoBindFields.forEach(el=>{
				if(el.component==item.__config__.formId){
				  item.__config__.defaultValue= data[el.bindField];
				}
			  })
		  }else{
			 if(autoBindFields.hasOwnProperty(item?.__config__?.formId)){
			   //按绑定的自定义字段赋值
			   item.__config__.defaultValue = data[autoBindFields[item.__config__.formId]];
			 } 
		  }
        }
      });
    },
    selfSetDefaultVal(fields,autoBindFields,data,value, formId){
      fields.map((item,index)=>{
        if(item?.__config__?.componentName == 'avue-tabs'){
          let childrenObj = item?.__config__?.childrenObj || {};
          for(let key in childrenObj){
            let children = childrenObj[key];
            this.selfSetDefaultVal(children,autoBindFields,data,value, formId);
          }
        }else{
          if(item?.__config__?.formId == formId){
            item.__config__.defaultValue = value;
			item.__config__.showValue = data;
          }
        }
		
			
      });
    },
	    defaultValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (conf.readonly) {
          //只读属性
          callback();
        }
        if (defaultValue) {
          callback();
        } else {
          const msg =
            conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder;
          callback(new Error(msg));
        }
      };
    },
    organizationTreeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (defaultValue) {
          callback();
        } else {
          const msg =`${conf.__config__.label}不能为空`;
          callback(new Error(' '));
        }
      };
    },
    financialValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
         const msg =
            conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder;
        if(defaultValue===''){
          callback(new Error(msg));
        }
        if (defaultValue>=0) {
          callback();
        } else {
         
          callback(new Error(msg));
        }
      };
    },
    
    quantityValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if(conf.readonly){//只读属性
          callback()
        }else{
          let ruleMessage = '';
          if(conf.min&&conf.max){
            ruleMessage = `${conf.__config__.label}最小数量为${conf.min}，最大数量为${conf.max}`;
            if(defaultValue&&(defaultValue.length<conf.min||defaultValue.length>conf.max)){
              callback(new Error(ruleMessage));
            }else{
              if(conf.min){
                ruleMessage = `${conf.__config__.label}最小数量为${conf.min}`;
                if(defaultValue&&defaultValue.length<conf.min){
                  callback(new Error(ruleMessage));
                }else{
                  callback()
                }
              }else if(conf.max){
                 ruleMessage = `${conf.__config__.label}最大数量为${conf.max}`;
                if(defaultValue&&defaultValue.length>conf.max){
                  callback(new Error(ruleMessage));
                }else{
                  callback()
                }
              }else{
                callback()
              }
               
            }
          }
        }
      };
    },
    patternValidator(pattern, msg,conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (conf.readonly) {
          //只读属性
          callback();
        }
        if (pattern.test(defaultValue)) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    switchValidator(conf) {
      return (rule, value, callback) => {
         callback();
      };
    },
    uploadValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        if(conf.__config__.defaultValue){
          callback();
        }else{
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须上传！";
          callback(new Error(msg));
        }
      };
    },
    checkboxValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
        if (defaultValueArr.length === 0) {
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder);
          callback(new Error(msg));
        }else{
          callback();
        }
      };
    },
    daterangeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
        const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须填写！";
        if(defaultValueArr&&Array.isArray(defaultValueArr)){
          if (defaultValueArr.length === 0) {
          callback(new Error(msg));
        }else{
          callback();
        }
        }else{
            callback(new Error(msg));
        }
      };
    },
    timerangeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须填写！";
        if(defaultValueArr&&Array.isArray(defaultValueArr)){
          if (defaultValueArr.length > 0) {
            if (defaultValueArr[0] == "") {
              callback(new Error(msg));
            }
            else {
              callback();
            }
          }else {
            callback(new Error(msg));
          }
        }else {
          callback(new Error(msg));
        }
        
      };
    },
    changeData() {
      const self = this // 规则验证需要绑定vue实例this
      this.formConf.fields.forEach((cur, fieldsIndex) => {
        if (
          cur.__config__.componentName &&
          cur.__config__.componentName == "avue-tabs"
        ) {
          if (cur.__config__ && cur.__config__.childrenObj) {
            let obj = cur.__config__.childrenObj;
            for (var i in obj) {
              if (obj[i].length > 0) {
                obj[i].forEach((ele1, cindex) => {
                  let config2 = ele1.__config__;
                  //表单提交数据（tablename绑定）
                    if (!this.formOperationObject.formModel[config2.bindTable]) {
                      this.formOperationObject.formModel[config2.bindTable] = {}
                    }
                    if (!this.formOperationObject.mainTableName) {
                      if (!config2.componentName ||config2.componentName !== 'table') {
                        this.formOperationObject.mainTableName = config2.bindTable
                      }
                    }
                  if (config2.componentName && config2.componentName === 'table'){
                      this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ].__config__.defaultValue = {
                          dynamic: [],
                        };
                      if (this.formData[config2.bindTable]) {
                          this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ].__config__.defaultValue = {
                            dynamic: this.formData[config2.bindTable],
                          };
                      }
                  }else{
                    if (config2.tag === 'el-upload') {//上传控件默认文件上传字段
                      this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ].__config__.defaultValue = "";
                      }
                      //数据回显
                      if (this.formData&&JSON.stringify(this.formData) !== '{}') {
                        this.setDefaultValue(cur,fieldsIndex);
                      }
                      if (ele1.__info__ === true && ele1.__type__ === 'info') {//信息体 赋值
                        this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag = 'info';
                      }
                      //表单规则创建
                    if (config2.required) {
                      let regList =  []
                      let trigger = 'change'
                      let validatorStr = 'default'
                      if (ComponentList[config2.tag]) {
                        trigger = ComponentList[config2.tag].rule.trigger
                          ? ComponentList[config2.tag].rule.trigger
                          : 'change'
                        validatorStr = ComponentList[config2.tag].rule.validatorStr
                          ? ComponentList[config2.tag].rule.validatorStr
                          : 'default'
                      }
                      let validator =  this.defaultValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                      if (validatorStr === "upload") {
                        validator = this.uploadValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                      }
                      else if(validatorStr === "switch"){
                        validator = this.switchValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                      }
                      else if (validatorStr === "checkbox") {
                        validator = this.checkboxValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                      }

                      // let validator = validatorStr === 'upload'?uploadValidator:defaultValidator
                      // 时间区间 日期区间 都是数组类型
                    if(config2.tag=='el-time-picker'&&config2.avueType=='timerange'){
                       validator = this.timerangeValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                    }
                    if(config2.tag=='el-date-picker'&&config2.avueType=='daterange'){
                       validator = this.daterangeValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                    }
                    if(config2.tag=='avue-input-tree'){
                       validator = this.organizationTreeValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                    }
                    if(ele1.type&&ele1.type === "number"){
                        validator = this.financialValidator(this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]);
                      }
                       const requiredJson = {
                        fieldsIndex: fieldsIndex,
                        required: config2.required,
                        trigger,
                        validator
                      }
                      regList.push(requiredJson)
                      //添加 多选框 最小数量 最大数量
                      if(config2.tag=='el-checkbox-group'){
                        if(ele1.min||ele1.max){
                          const quantityJson = {
                            fieldsIndex: fieldsIndex,
                            required: config2.required,
                            trigger,
                            validator:quantityValidator
                          };
                          regList.push(quantityJson)
                        }
                      }
                          //添加正则验证
                          if (
                            config2.regList &&
                            config2.regList.length > 0
                          ) {
                            config2.regList.forEach(item => {
                              if (item.pattern) {
                                regList.push({
                                  required: true,
                                  fieldsIndex: fieldsIndex,
                                  validator:  this.patternValidator(
                                    eval(item.pattern),
                                    item.message ? item.message : "验证不通过",
                                    this.formConf.fields[fieldsIndex].__config__.childrenObj[i][
                          cindex
                        ]
                                  ),
                                  trigger: "change"
                                });
                              }
                            });
                          }
                          this.formOperationObject.formRules[config2.bindTableField] = regList;
                    }
                  }
                })
              }
            }
          }
        }else{
           const config = cur.__config__
        this.formConf.fields[fieldsIndex].__config__.edit = true;
        //表单提交数据（tablename绑定）
        if (!this.formOperationObject.formModel[config.bindTable]) {
          this.formOperationObject.formModel[config.bindTable] = {}
        }

        if (config.componentName && config.componentName === 'table'){
           this.formConf.fields[fieldsIndex].__config__.defaultValue = {
                dynamic: [],
              };
        }
        if (!this.formOperationObject.mainTableName) {
          if (!config.componentName ||config.componentName !== 'table') {
            this.formOperationObject.mainTableName = config.bindTable
          }
        }

        if (config.tag === 'el-upload') {//上传控件默认文件上传字段
        this.formConf.fields[fieldsIndex].__config__.defaultValue = "";
        }
         //数据回显
        if (this.formData&&JSON.stringify(this.formData) !== '{}') {
          this.setDefaultValue(cur,fieldsIndex);
        }
        if (cur.__info__ === true && cur.__type__ === 'info') {//信息体 赋值
          this.formConf.fields[fieldsIndex].__config__.tag = 'info';
        }

        //表单规则创建
        if (config.required) {
          let regList =  []
          let trigger = 'change'
          let validatorStr = 'default'
          if (ComponentList[config.tag]) {
            trigger = ComponentList[config.tag].rule.trigger
              ? ComponentList[config.tag].rule.trigger
              : 'change'
            validatorStr = ComponentList[config.tag].rule.validatorStr
              ? ComponentList[config.tag].rule.validatorStr
              : 'default'
          }
          let validator =  this.defaultValidator(this.formConf.fields[fieldsIndex]);
          if (validatorStr === "upload") {
            validator = this.uploadValidator(this.formConf.fields[fieldsIndex]);
          }
          else if(validatorStr === "switch"){
            validator = this.switchValidator(this.formConf.fields[fieldsIndex]);
          }
          else if (validatorStr === "checkbox") {
            validator = this.checkboxValidator(this.formConf.fields[fieldsIndex]);
          }
          
          if(cur.type&&cur.type === "number"){
            validator = this.financialValidator(this.formConf.fields[fieldsIndex]);
          }

            // 时间区间 日期区间 都是数组类型
            if(config.tag=='el-time-picker'&&config.avueType=='timerange'){
                validator = this.timerangeValidator(this.formConf.fields[fieldsIndex]);
            }
            if(config.tag=='el-date-picker'&&config.avueType=='daterange'){
                validator = this.daterangeValidator(this.formConf.fields[fieldsIndex]);
            }
            if(config.tag=='avue-input-tree'){
                validator = this.organizationTreeValidator(this.formConf.fields[fieldsIndex]);
            }
          // let validator = validatorStr === 'upload'?uploadValidator:defaultValidator
          const requiredJson = {
            fieldsIndex: fieldsIndex,
            required: config.required,
            trigger,
            validator
          }
          regList.push(requiredJson)
          //添加 多选框 最小数量 最大数量
          if(config.tag=='el-checkbox-group'){
            if(cur.min||cur.max){
              const quantityJson = {
                fieldsIndex: fieldsIndex,
                required: config.required,
                trigger,
                validator:quantityValidator
              };
              regList.push(quantityJson)
            }
          }
              //添加正则验证
              if (
                config.regList &&
                config.regList.length > 0
              ) {
                config.regList.forEach(item => {
                  if (item.pattern) {
                    regList.push({
                      required: true,
                      fieldsIndex: fieldsIndex,
                      validator:  this.patternValidator(
                        eval(item.pattern),
                        item.message ? item.message : "验证不通过",
                        this.formConf.fields[fieldsIndex]
                      ),
                      trigger: "change"
                    });
                  }
                });
              }
              this.formOperationObject.formRules[config.bindTableField] = regList;
        }
        }
      
       
      })
    },
    setDefaultValueByTabs(config,formData){
      let childrenObj = config.childrenObj || {};
      for(let key in childrenObj){
        let children = childrenObj[key];
        children.map(item=>{
          if(item?.__config__?.componentName == 'table'){
            item.__config__.defaultValue = {
              dynamic: formData[item.__config__.bindTable],
            };
          }else{
            if (formData[item.__config__.bindTable]&&
              formData[item.__config__.bindTable][
                item.__config__.bindTableField
              ]
            ) {
              item.__config__.defaultValue = formData[item.__config__.bindTable][
                item.__config__.bindTableField
              ];
              if (
                item.__config__.tag ===
                  "el-checkbox-group"
              ) {
                let configVal =formData[item.__config__.bindTable][
                item.__config__.bindTableField
                ];
                if(configVal.includes(',')){
                   item.__config__.defaultValue = configVal.split(",");
                }else{
                   item.__config__.defaultValue = [configVal];
                }
              }
              else if (
                  item.__config__.tag ===
                  "el-date-picker" ||
                  item.__config__.tag ===
                  "el-time-picker"
              ) {
                let configVal =formData[item.__config__.bindTable][
                item.__config__.bindTableField
                ];
                if(configVal.includes(',')){
                   item.__config__.defaultValue = configVal.split(",");
                }else{
                   item.__config__.defaultValue = configVal;
                }
              }
            }
          }
        });
      }
    },
    setDefaultValue(cur,fieldsIndex){
          const config = cur.__config__;
          if (
            this.formData[cur.__config__.bindTable]&&config.componentName&&config.componentName === "table"
          ) {
              this.formConf.fields[fieldsIndex].__config__.defaultValue = {
                dynamic: this.formData[cur.__config__.bindTable],
              };
          }
          if(config.componentName&&config.componentName === 'avue-tabs'){
            this.setDefaultValueByTabs(config,this.formData);
          }else{
             if(this.formConf.fields[fieldsIndex].__config__.tag=='el-checkbox-group'){
                let configVal = this.formData[cur.__config__.bindTable][cur.__config__.bindTableField];
               
                 if(configVal.includes(',')){
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = configVal.split(",");
                }else{
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = [configVal];
                }

             }else if(this.formConf.fields[fieldsIndex].__config__.tag=='el-date-picker'){
                let configVal = this.formData[cur.__config__.bindTable][cur.__config__.bindTableField];
                if(configVal.includes(',')){
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = configVal.split(",");
                }else{
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = configVal;
                }
             }else if(this.formConf.fields[fieldsIndex].__config__.tag=='el-time-picker'){
                let configVal = this.formData[cur.__config__.bindTable][cur.__config__.bindTableField];
                if(configVal.includes(',')){
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = configVal.split(",");
                }else{
                   this.formConf.fields[fieldsIndex].__config__.defaultValue = configVal;
                }
             }else{
               if(this.formData[cur.__config__.bindTable]&&this.formData[cur.__config__.bindTable][cur.__config__.bindTableField]){
                  this.formConf.fields[fieldsIndex].__config__.defaultValue = this.formData[cur.__config__.bindTable][cur.__config__.bindTableField]
               }
             }
          }
          
    },
    renderForm(createElement) {
      return this.formConf.fields.map((scheme, index) => {
        const config = scheme.__config__
        if(config.layout === 'colFormItem'){
           return this.renderColFormItem(createElement, config.layout, scheme, index)
        }else if(config.layout === 'rowFormItem'){
           return this.renderRowFormItem(createElement, config.layout, scheme, index)
        } else {
          return ''
        }
      })
    },
	handleFilterableClick(scheme) {
	  let conf = scheme.__config__;

	    let params = {};
	    params.title = conf.label + this.$t('optionRecord');
	    params.model = scheme.__vModel__;
	    params.formId = conf.formId;
	    params.dataType = conf.dataType;
		params.avueType = conf.avueType;
	    switch (conf.dataType) {
	      case "dataSource":
	        params.dataSource = conf.dataSource;
	        params.tabName = "base";
	        break;
	      case "dataSql":
	        params.dataSource = conf.database;
	        params.tabName = "sql";
	        params.sqlStr = conf.sql;
	        break;
	      case "dataItem":
	        params.dataSource = conf.dataItem;
	        params.fields = ["F_ItemName", "F_ItemValue"];
	        params.tabName = "item";
			conf.saveField='F_ItemValue'
	        break;
	    }
	    params.showField = conf.showField;
	    params.saveField = conf.saveField;
	    params.autoBindFields = conf.autoBindFields;
		params.defaultValue=conf.defaultValue;
	    this.$event.$emit("openFilterableDataDialog", params);

	},
     renderColFormItem(createElement, item, scheme, fieldsIndex){
        const config = scheme.__config__
        let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
        if (config.showLabel === false) {
          labelWidth = '0'
        }
        let renderTag = ComponentList[config.tag]?ComponentList[config.tag].renderTag:'ElComponent';
		
        const vnodes = createElement(renderTag, {props: { fieldsIndex, formConf: this.formConf, curFormId: config.formId, isEdit: this.isEdit  }});
		let showNode=''
		if(config.tag=="el-mutiple-input"){
			showNode=createElement('el-input',{
				props:{
					value:config.showValue,
					'suffix-icon':'el-icon-more'
				},
				attrs:{
					placeholder:scheme.placeholder
				},
				on:{
					focus:()=>this.handleFilterableClick(scheme)
				}
			})
		}

    let lgmarkString = '';
    /**
     * author:tzx
     * time : 2021.10.30
     * desc ：多语言翻译 当前form label
     */
    if(config.F_LgMarkCode === '' || config.F_LgMarkCode === null|| config.F_LgMarkCode === undefined){
      lgmarkString = config.label
    }
    else{
      lgmarkString = this.$t(config.F_LgMarkCode);
    }
		if(config.tag=="el-mutiple-input"){
			return (
			  <el-col span={config.span}>
			    <el-form-item
			      label-width={labelWidth}
			      prop={config.bindTableField}
			      label={config.showLabel ? lgmarkString  : ''}
			    >
			      {showNode}
				  <el-form-item
				    prop={config.bindTableField}
					style="display:none"
				  >
				    {vnodes}
				  </el-form-item>
			    </el-form-item>
			  </el-col>
			)
		}else{
			return (
			  <el-col span={config.span}>
			    <el-form-item
			      label-width={labelWidth}
			      prop={config.bindTableField}
			      label={config.showLabel ? lgmarkString  : ''}
			    >
			      {vnodes}
			    </el-form-item>
			  </el-col>
			)
		}
		
    },
    renderRowFormItem(createElement, item, scheme, fieldsIndex){
       let child = this.renderChildren(createElement,scheme,fieldsIndex)
       let slots = child;
        if(scheme.__config__.componentName && scheme.__config__.componentName === 'table'){
            return child
        } else if (scheme.type === 'flex') { // 如果是表格类型
          slots = this.renderFlexRow(scheme,child);
        }
        return (
          <el-col span={scheme.span}>
            <el-row gutter={scheme.gutter}>{slots}</el-row>
          </el-col>
        )
    },
    renderChildren(createElement,scheme,fieldsIndex) {
      const config = scheme.__config__
      if (config.componentName && config.componentName === 'table') {
        return this.renderTable(createElement,config,fieldsIndex);
      }
      //avue-tabs 绘制
      if (config.componentName && config.componentName === 'avue-tabs'){
        return this.renderTabs(createElement,config,fieldsIndex);
      }
      if (!Array.isArray(config.children)){
         return null
      }
      return this.renderForm(config.children)
    },
    renderTable(createElement,config,fieldsIndex){
      return createElement('CustomeTable', {props: { fieldsIndex, formConf: this.formConf, isEdit: this.isEdit },ref:'avueTable'+config.formId});
    },
    renderTabs(createElement,config,fieldsIndex){
      return createElement('CustomeTabs', {props: { fieldsIndex, formConf: this.formConf, isEdit: this.isEdit },ref:'FormTab'+config.formId });
    },
    renderFlexRow(scheme,child){
      return (
            <el-row
              type={scheme.type}
              justify={scheme.justify}
              align={scheme.align}
            >
              {child}
            </el-row>
          );
    },
    getInterceptFields(fields){
      fields.map(item=>{
        if(item?.__config__?.componentName == 'avue-tabs'){
          let childrenObj = item?.__config__?.childrenObj || null;
          if(!childrenObj) return;
          for(let key in childrenObj){
            let children = childrenObj[key];
            (children && children.length) && (this.getInterceptFields(children));
          }
        }else if(item?.__config__?.componentName == 'table'){
          let children = item?.__config__?.children;
          (children && children.length) && (this.getInterceptFields(children));
        }else{
          if(item?.__config__?.tag == 'el-checkbox-group'){
            this.checkboxField[item?.__config__?.bindTableField] = item?.__config__?.bindTableField;
          }
        }
      })
    },
    async submitForm() {//父页面提交表单
		let validataArry = []
		for(const el in this.$refs){
      if(el.includes('FormTab')){
          	for(const el2 in this.$refs[el].$refs){
              if(el2.includes('avueTable')){
                let value = this.$refs[el].$refs[el2].getDynamicDefaultValue();
                if(value&&value.length>0){
                    const promise4  = new Promise((resolve,reject) => {
                      this.$refs[el].$refs[el2].validate(valid =>{
                          resolve(valid)
                        })
                    })			
                    validataArry.push(promise4)
                }
              }else{
                const promise2  = new Promise((resolve,reject) => {
                      this.$refs[el].$refs[el2].validate(valid =>{
                        resolve(valid)
                      })
                    })			
                validataArry.push(promise2)
              }
            }
        }else if(el.includes('avueTable')){
          let value = this.$refs[el].getDynamicDefaultValue();
          if(value&&value.length>0){
              const promise3  = new Promise((resolve,reject) => {
                this.$refs[el].validate(valid =>{
                    resolve(valid)
                  })
              })			
              validataArry.push(promise3)
          }
        }else{
          const promise  = new Promise((resolve,reject) => {
          this.$refs[el].validate(valid =>{
              resolve(valid)
            })
          })			
			    validataArry.push(promise)
      }
		}
		let res=await Promise.all(validataArry)
		if(res.includes(false)){
       return false
    }
		const newObj = {}
		this.getInterceptFields(this.formConf.fields);
		
		this.formConf.fields.forEach((el) => {
		  if (el.__config__.componentName === 'table') {
		
		    if (!newObj[el.__config__.bindTable]) {
		      newObj[el.__config__.bindTable] = []
		    }
		
		     let tmp = el.__config__.defaultValue.dynamic
		    let self = this;
		    if(tmp&&tmp.length>0){
		      tmp.forEach(function(item) {
		      let itemChild = { ...item }
		       delete itemChild._index
		      for (let [key, value] of Object.entries(itemChild)) {
		        if(key.includes('$')){
		          delete itemChild[key];
		        }else{
		          if(Array.isArray(value)){
		              itemChild[key] = value.join(",")
		          }
		        }
		      }
		      self.setInterceptVal(itemChild);
		      newObj[el.__config__.bindTable].push(itemChild)
		    })
		    }
		    
		  } else {
		    if(el?.__config__?.componentName == 'avue-tabs'){
		        let fieldInfo = this.getFieldsByTab(el?.__config__?.childrenObj,newObj);
		        let bindTable = '';
		        if(fieldInfo && fieldInfo.length){
		          bindTable = fieldInfo[0].bindTable;
		          if (!newObj[bindTable]) {
		            newObj[bindTable] = {}
		          }
		        }
		        fieldInfo.map(item=>{
              if(item.defaultValue&&Array.isArray(item.defaultValue)){
                 newObj[bindTable][item.bindTableField] = item.defaultValue.join(",");
              }else{
                   newObj[bindTable][item.bindTableField] = item.defaultValue;
              }
		        });
		    }else{
		      if (el.__config__.bindTable) {
		        if (!newObj[el.__config__.bindTable]) {
		          newObj[el.__config__.bindTable] = {}
		        }
            if(el.__config__.defaultValue&&Array.isArray(el.__config__.defaultValue)){
                 newObj[el.__config__.bindTable][el.__config__.bindTableField] = el.__config__.defaultValue.join(",");
              }else{
                newObj[el.__config__.bindTable][el.__config__.bindTableField] = el.__config__.defaultValue;
              }
		      }
		    }
		  }
		})
		var formParams = {}
		for (const key in newObj) {
		  // formParams[key] = JSON.stringify(newObj[key])
		  formParams[key] = newObj[key];
		}
		var mainParams = {
		  f_mobile: this.userInfo.F_Account
		}
		if (this.formInfos?.SchemeInfo) {
		  mainParams.F_FormId = this.formInfos.SchemeInfo.F_Id // 表单ID(后端需要)
		  mainParams.F_Name = this.formInfos.SchemeInfo.F_Name // 表单名
		}
		var params = Object.assign(mainParams, formParams)
		return params
    },
    setInterceptVal(obj){
      for(let key in obj){
        //复选框  提交到后端需转成字符串
        if(this.checkboxField.hasOwnProperty(key)){
          obj[key] = Array.isArray(obj[key])
                      ? obj[key].join(",")
                      : obj[key];
        }
      }
    },
    getFieldsByTab(childrenObj,newObj){
      let _arr = [];
      if(!childrenObj || childrenObj instanceof Object){
        for(let key in childrenObj){
          let children = childrenObj[key];
          children.map(item=>{
            if(item?.__config__?.componentName == 'table'){
              // var _tmp = item.__config__.defaultValue.dynamic
              let children = item?.__config__?.children || [];
              let bindTable = '';
              
              children.map((el)=>{
                bindTable = el.__config__.bindTable;
                if (!newObj[el.__config__.bindTable]) {
                  newObj[el.__config__.bindTable] = []
                }
              });
              let self = this;
              let tmp = item.__config__.defaultValue.dynamic;
              if(tmp&&tmp.length>0){
              tmp.forEach(function(item) {
                let itemChild = { ...item }
                delete itemChild._index
                for (let [key, value] of Object.entries(itemChild)) {
                  if(key.includes('$')){
                    delete itemChild[key];
                  }else{
                    if(Array.isArray(value)){
                        itemChild[key] = value.join(",")
                    }
                  }
                }
                self.setInterceptVal(itemChild);
                newObj[bindTable].push(itemChild)
              })
              }

            }else {
              if(item?.__config__?.bindTable && item?.__config__?.bindTableField){
                let _obj = {};
                _obj.bindTableField = item?.__config__?.bindTableField;
                _obj.defaultValue = item?.__config__?.defaultValue;
                _obj.bindTable = item?.__config__?.bindTable;
                _obj.tag = item?.__config__?.tag;
                _arr.push(_obj);
              }
            }
          });
        }
      }
      return (()=>{ return _arr; })()
    }
  }
}
</script>
<style scoped>
 div /deep/ .el-table__body,  div /deep/ .el-table__footer,  div /deep/ .el-table__header{
  width: 100% !important;
}
.el-form-item{
  margin-top: 0;
  margin-bottom: 18px!important;
}
div /deep/ .avue-input-tree{
  display: block;
}
</style>
